package top.xmln.githublogin_demo.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import top.xmln.githublogin_demo.model.GithubModel;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.HashMap;
import java.util.Map;

@Service
public class RequestService {
    @Resource
    GithubModel githubModel;
    @Resource
    private ObjectMapper json;

    /**
     * 获取授权码
     *
     * @param code 授权码
     * @return 用户信息
     */
    public Map<String, Object> sendAuthorizationCode(String code) {
        Map<String, String> resp = new HashMap<>();

        // 获取某个用户的令牌
        try {
            // 构建请求
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("https://github.com/login/oauth/access_token");
            stringBuilder.append("?client_id=").append(githubModel.getClientId());
            stringBuilder.append("&client_secret=").append(githubModel.getClientSecret());
            stringBuilder.append("&code=").append(code);
            String URL = stringBuilder.toString();
            HttpRequest request = HttpRequest
                    .newBuilder(URI.create(URL))
                    .POST(HttpRequest.BodyPublishers.noBody())
                    .build();

            // 发送请求
            HttpResponse<String> response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());

            // 解析响应
            for (String s : response.body().split("&")) {
                String[] split = s.split("=");
                if (split.length == 2) {
                    resp.put(split[0], split[1]);
                } else {
                    resp.put(split[0], "");
                }
            }
        } catch (IOException | InterruptedException e) {
            throw new RuntimeException(e);
        }

        // 根据令牌获取用户信息
        try {
            // 构建请求
            HttpRequest request = HttpRequest
                    .newBuilder(URI.create("https://api.github.com/user"))
                    .header("Authorization", "Bearer " + resp.get("access_token"))
                    .GET()
                    .build();

            // 发送请求
            HttpResponse<String> response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());

            // 解析响应
            return json.readValue(response.body(), Map.class);
        } catch (IOException | InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取授权链接
     *
     * @return 授权链接
     */
    public String getAuthorizationLink() {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("https://github.com/login/oauth/authorize");
        stringBuilder.append("?client_id=").append(githubModel.getClientId());
        stringBuilder.append("&redirect_uri=").append(githubModel.getRedirectUri());
        return stringBuilder.toString();
    }
}
